How to Write a Query to Find the Second Highest Salary in SQL Server?
How to Write a Query to Find the Second Highest Salary in SQL Server?
442
15-Jul-2024
Updated on 16-Jul-2024
Ravi Vishwakarma
16-Jul-2024To retrieve the second-highest salary from a SQL Server table, you can use a subquery with the
ROW_NUMBER()function. Here's how you can do it:In this query:
Inner Query (
SalaryRanked): This subquery selects theSalarycolumn from your table (YourTableName) and assigns a row number (RowNum) to each row based on the descending order ofSalary.Outer Query: The outer query selects the
Salaryfrom theSalaryRankedsubquery where theRowNumequals2, which corresponds to the second-highest salary.Make sure to replace
YourTableNamewith the actual name of your table andSalarywith the actual column name containing the salaries in your database schema. This query will give you the second-highest salary from your table.Example
OR
Read more
Write a basic SELECT statement to retrieve data from a SQL Server table.
Help with Writing a Subquery to Get Aggregate Data in SQL Server
SQL Query to Calculate Running Total in SQL Server